package cases

import (
  "errors"
  "github.com/gin-gonic/gin"
  "go.mongodb.org/mongo-driver/bson"
  "go.mongodb.org/mongo-driver/mongo"
  "livefind/model/cases"
  caseReq "livefind/service/cases/request"
  caseRsp "livefind/service/cases/response"
  "livefind/utils"
  "livefind/utils/logger"
)

type CaseService struct {
}

//@author: [Srim_ycb]
//@function: Create
//@description: 新建案件
//@param: c cases.CaseQuery
//@return: err error
func (CaseService *CaseService) Create(req caseReq.CaseCreateReq, c *gin.Context) (err error) {
  info := cases.CaseInfo{}
  casesQuery := req.ConvertCreate2Query(c)
  filter := bson.M{
    "creator": casesQuery.Creator,
    "$or": bson.A{
      bson.M{
        "caseNo": casesQuery.CaseNo,
      },
      bson.M{
        "caseName": casesQuery.CaseName,
      },
    },
  }
  _, err = caseModel.FindCaseByFilter(filter)
  if err != nil {
    if err != mongo.ErrNoDocuments {
      logger.Error(err.Error(), err)
      return errors.New("创建案件失败")
    }
  } else {
    return errors.New("该案件号或案件名已存在")
  }

  utils.StructAssign(&info, casesQuery)

  err = caseModel.Create(info)

  if err != nil {
    err = errors.New("创建案件失败")
  }
  return err
}

//@author: [Srim_ycb]
//@function: List
//@description: 获取案件列表
//@param: l cases.CaseQuery
//@return: casesInfo {[]object} []cases.CaseInfo, err error
func (CaseService *CaseService) List(req caseReq.CaseListReq) (rsp caseRsp.CasesListRsp, err error) {
  caseQuery := req.ConvertList2Query("createTime")
  if caseQuery.Creator == "" {
    caseQuery.Creator = "测试员1"
  }
  filter := bson.M{
    "creator": caseQuery.Creator,
  }
  sorted := bson.D{{caseQuery.SortField, caseQuery.SortRule}}

  casesInfo, err := caseModel.List(filter, sorted, caseQuery.Skip, caseQuery.Limit)

  if err != nil {
    return rsp, errors.New("获取案件列表失败")
  }
  totalNum, err := caseModel.CountDocuments(filter)
  if err != nil {
    return rsp, errors.New("获取案件列表失败")
  }

  rsp = caseRsp.ConvertList2Rsp(casesInfo, req.Page, req.PageSize, totalNum)
  return rsp, err
}

//@author: [Srim_ycb]
//@function: GetById
//@description: 获取单条案件
//@param: id string
//@return: casesInfo {[]object} []cases.CaseInfo, err error
func (CaseService *CaseService) GetById(req caseReq.CaseGetReq) (rsp caseRsp.CaseGetRsp, err error) {
  mid, err := req.ConvertGetById2Query()
  if err != nil {
    return rsp, errors.New("案件ID错误")
  }
  filter := bson.M{
    "_id": mid,
  }

  caseInfo, err := caseModel.GetById(filter)

  if err != nil {
    return rsp, errors.New("获取案件信息失败")
  }
  rsp = caseRsp.ConvertGetById2Rsp(caseInfo)
  return rsp, err
}
